import Vue from 'vue'
import Vuex from 'vuex'
import { login } from '@/api/user'

Vue.use(Vuex)

//用来全局定义一些共享的数据状态
const state = {
    name: '张三',
    user: {
        name: '李四',
        age: 18
    },
    userList: [
        { name: '张三', age: 18 },
        { name: '李四', age: 19 }

    ],
    isLoggedIn: false, // 是否登录
};

//定义方法修改state中的数据
const mutations = {
    updateName(state, name) {
        state.name = name;
    },
    updateUser(state, user) {
        state.user = user;
    },
    addUser(state, user) {
        state.userList.push(user);
    },
    SET_LOGGED_IN(state, isLoggedIn) {
        state.isLoggedIn = isLoggedIn;
        localStorage.setItem('isLoggedIn', isLoggedIn); // 存储到localStorage
    },
    SET_USER(state, user) {
        state.user = user;
        localStorage.setItem('user', JSON.stringify(user)); // 存储到localStorage
    }
}
// 响应组件中的事件
const actions = {
    login({ commit }, user) {
        // 这里可以调用API进行登录验证
        // login(user).then(response => {

        // })
        if (user.username === 'admin' && user.password === '123') {
            commit('SET_LOGGED_IN', true);
            commit('SET_USER', user);
            return true;
        } else {
            return false;
        }
    },
}

// 用来将state数据进行加工
const getters = {
    getAllAges(state) {
        let sumAge = 0;
        state.userList.forEach(user => {
            sumAge += user.age;
        })
        return sumAge;
    }
}



//创建store对象
const store = new Vuex.Store({
    state,
    mutations,
    actions,
    getters
});
//3.暴露store对象
export default store